package com.mongodb.service.Impl;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.pojo.Book;
import com.mongodb.service.BookService;
import jakarta.annotation.Resource;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;
import java.util.regex.Pattern;

public class BookServiceImpl implements BookService {
	@Resource
	MongoTemplate mongoTemplate;
	@Override
	public List<Book> findAllBooks() {
		return mongoTemplate.findAll(Book.class,"mybook");
	}

	@Override
	public Book findBookById(Integer id) {
		return mongoTemplate.findById(id,Book.class,"mybook");
	}

	@Override
	public Book addBook(Book book) {
		return mongoTemplate.insert(book,"mybook");
	}

	@Override
	public UpdateResult updateBook(Book book) {
		Query query=new Query();
		query.addCriteria(Criteria.where("id").is(book.getId()));
		Update update=new Update();
		update.set("name",book.getName());
		update.set("author",book.getAuthor());
		update.set("category",book.getCategory());
		update.set("description",book.getDescription());
		update.set("imgurl",book.getImgurl());
		update.set("pnum",book.getPnum());
		update.set("price",book.getPrice());
		update.set("sales",book.getSales());
		return mongoTemplate.updateFirst(query,update,"mybook");
	}

	@Override
	public DeleteResult deleteBook(Integer id) {
		Query query=new Query();
		query.addCriteria(Criteria.where("id").is(id));
		return mongoTemplate.remove(query,Book.class,"mybook");
	}

	@Override
	public List<Book> findLike(String name) {
		Pattern pattern=Pattern.compile("^.*"+name+".*$",Pattern.CASE_INSENSITIVE);
		Query query=new Query(Criteria.where("name").regex(pattern));
		return mongoTemplate.find(query,Book.class,"mybook");
	}
}
